package ${model_package_controller};

/**
 * Created by lewis on ${.now}.
 */

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.models.constant.JafCoreConstant;
import com.models.constant.MessageConstant;
import com.modules.persistence.DynamicSpecifications;
import com.modules.utils.MenuMapping;
import com.modules.utils.ResourceMapping;
import com.modules.utils.ResourceMapping.Operation;
import com.modules.web.CRUDController;
import ${name};
import ${model_package_service}.${model_name}Service;

@Controller
@RequestMapping("/${model_name_entity}/${model_name_entity}Info")
@MenuMapping(name = "${model_name_entity}信息", operator = "${model_name_entity}10", parentOperator = "")
public class ${model_name}Controller extends CRUDController{
    private static Logger logger	= LoggerFactory.getLogger(${model_name}Controller.class);

    
    
    @Autowired
    private ${model_name}Service ${model_name_entity}Service;

    @RequestMapping("/list")
    @RequiresPermissions ("${model_name_entity}:list")
    @ResourceMapping(name = "${model_name_entity}列表", operation = Operation.MENU)
    public String list(Model model){

        return "${model_name_entity}/${model_name_entity}List";
    }
    /*
     * 这个查询是跟页面按钮相关的操作是一个层级的
     * RequiresPermissions为了进行权限控制
     * **/
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @RequiresPermissions ("${model_name_entity}:list")//权限
    @ResponseBody
    public Map<String, Object> query(HttpServletRequest request) throws Exception {

        Page page = onPrepareQueryData(request);
        return  transferTo(page);
    }
    
    protected Page onPrepareQueryData(HttpServletRequest request) throws Exception {
    	Specification spec = DynamicSpecifications.bySearchFilter(request);//查询条件(基本查询条件)
    	//Specification spec = DynamicSpecifications.bySearchFilter(request,DynamicSpecifications.bulidSearchSpecFilter(new SearchFilter("EQ_name","**"),new SearchFilter("or","EQ_name","**")));//查询条件(基本查询条件)
        PageRequest pageRequest = DynamicSpecifications.buildPageRequest(request,null);//相关的分页
        Page<${model_name}> page = ${model_name_entity}Service.findAll(spec,pageRequest);
        return page;//用来查询相关的数据
    }

    @RequiresPermissions ("${model_name_entity}:add")//权限
    @ResourceMapping(name = "添加${model_name_entity}", operation = Operation.BUTTON)
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String showAddPage(Model model) {

        return "${model_name_entity}/${model_name_entity}Edit";
    }
    
    @RequiresPermissions ("${model_name_entity}:view")//权限
    @ResourceMapping(name = "${model_name_entity}信息查看", operation = Operation.BUTTON)
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String showViewPage(${model_key_type} ${model_key},  Model model) {
      
    	 return "${model_name_entity}/${model_name_entity}Edit";
    }

    /**
     * 返回编辑页面
     * @param id
     * @return 编辑页面
     */
    @RequiresPermissions ("${model_name_entity}:edit")
    @ResourceMapping(name = "${model_name_entity}信息编辑页面", operation = Operation.BUTTON)
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String showEditPage(${model_key_type} ${model_key},  Model model) {
        return "${model_name_entity}/${model_name_entity}Edit";
    }


    /**
     * 获取指定primary key的实体对象（数据库记录）
     */
    @RequiresPermissions (value={"${model_name_entity}:edit","${model_name_entity}:add","${model_name_entity}:view"},logical=Logical.OR)//权限跟其先关的操作是一样的
    @RequestMapping(value = "/edit/{${model_key}}")
    @ResponseBody
    public ${model_name} getEditData(@PathVariable ${model_key_type} ${model_key}) {
        ${model_name} ${model_name_entity} = null;
        try {
            ${model_name_entity} = ${model_name_entity}Service.get(${model_key});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ${model_name_entity} ;
    }
    /**
     * 保存是作为新建和编辑按钮的辅助性操作，可以认为保存是新建和保存下的子操作
     * 辅助操作的权限不用进行显示
     * */
    @RequiresPermissions (value={"${model_name_entity}:edit", "${model_name_entity}:add"},logical=Logical.OR)
    @RequestMapping(value = "/save")
    @ResponseBody
    public Map<String, Object> save(${model_name} ${model_name_entity}) {
        Map<String, Object> tips = new HashMap<String, Object>();
        try {
			String result = ${model_name_entity}Service.save${model_name}(${model_name_entity});
			//如果需要在不关闭窗口的情况下多次更新，则需要向页面回写version，打开下面的代码
			if (JafCoreConstant.OUT_OF_DATE.equals(result)){
				tips.put(MessageConstant.SUCCESS, false);
				tips.put(MessageConstant.MSG, MessageConstant.FAILURE_OUT_OF_DATE);
			}else{
				tips.put(MessageConstant.SUCCESS, true);
				tips.put(MessageConstant.MSG, MessageConstant.SUCCESS_SAVE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			tips.put(MessageConstant.SUCCESS, false);
			tips.put(MessageConstant.MSG, MessageConstant.FAILURE_SAVE);
		}
        return tips;
    }
    
    
    @RequiresPermissions ("${model_name_entity}:delete")//权限跟其先关的操作是一样的
    @RequestMapping(value = "/delete/{${model_key}}")
    @ResourceMapping(name = "${model_name_entity}信息删除", operation = Operation.BUTTON)
    @ResponseBody
    public Map<String,Object> delete(@PathVariable ${model_key_type} ${model_key}){
    	Map<String,Object> tips = new HashMap<String, Object>();
        try {
           ${model_name_entity}Service.delete${model_name}(${model_key});
    	   tips.put(MessageConstant.SUCCESS, true);
		   tips.put(MessageConstant.MSG, MessageConstant.SUCCESS_DELETE);
        }catch (Exception e) {
    	   e.printStackTrace();
    	   tips.put(MessageConstant.SUCCESS, false);
		   tips.put(MessageConstant.MSG, MessageConstant.FAILURE_DELETE);
        }
    	return tips;
    }
}